package org.linlinjava.litemall.web.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallPosAd;
import org.linlinjava.litemall.db.domain.LitemallStorage;
import org.linlinjava.litemall.db.service.LitemallPosAdService;
import org.linlinjava.litemall.db.service.LitemallStorageService;
import org.linlinjava.litemall.db.util.PageTools;
import org.linlinjava.litemall.web.vo.WebPosAdsVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class WebPosAdService {

    private final LitemallPosAdService litemallPosAdService;

    public final LitemallStorageService litemallStorageService;

    public ResponseUtil.Response posAdSByShopId(Integer shopId, Integer page, Integer limit) {
        List<LitemallPosAd> litemallPosAds = litemallPosAdService.list(Wrappers.lambdaQuery(LitemallPosAd.class).eq(LitemallPosAd::getIsOpen,1).orderByAsc(LitemallPosAd::getAddTime)).stream().filter(litemallPosAd -> {
            boolean result = LocalDateTime.now().isAfter(litemallPosAd.getStartTime()) && LocalDateTime.now().isBefore(litemallPosAd.getEndTime());
            if(!result){return false;}
            if (litemallPosAd.getType() == 0) {return true;}
            for (Integer id : litemallPosAd.getShopIds()) {return shopId.equals(id);}
            return false;
        }).map(posAdS->{
            WebPosAdsVO  webPosAdsVO = new WebPosAdsVO();
            List<LitemallStorage> litemallStorages = CollUtil.newArrayList();
            for (Integer integer : posAdS.getImgObj()) {
                litemallStorages.add(litemallStorageService.findById(integer));
            }
            webPosAdsVO.setImgUrlS(litemallStorages);
            BeanUtils.copyProperties(posAdS,webPosAdsVO);
            return webPosAdsVO;
        }).collect(Collectors.toList());
        PageTools pageTools =PageTools.builder().build();
        pageTools.pageTools(page,limit,litemallPosAds);
        return ResponseUtil.ok(pageTools);
    }
}
